<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import { useMessage } from 'naive-ui';
import { createProForm, zhCN } from 'pro-naive-ui';
import { $t } from '@/locales';
import ConfigProvider from '../../ConfigProvider.vue';
import type { UploadFileInfo } from 'naive-ui';

// 导入API（API返回单图URL：string | null）
import {
  fetchGetCompanyInfo,
  fetchSaveCompanyInfo,
  fetchUploadFile,
  type Api
} from '@/service/api/systemCompany';

// 1. 组件内部用：数组格式（适配ProUpload，避免map错误）
type ComponentFormValues = {
  companyName: string;
  companyPhone: string;
  companyEmail: string;
  officialAccountLink: string;
  companyLogo: UploadFileInfo[]; // 组件必须数组
  officialAccountImg: UploadFileInfo[]; // 组件必须数组
};

// 2. API交互用：单图URL格式（匹配API返回）
type ApiFormValues = Api.SystemCompany.CompanyInfo;

const submitting = ref(false);
const message = useMessage();

// 创建组件用的表单（初始空数组，适配组件）
const form = createProForm<ComponentFormValues>({
  initialValues: {
    companyName: '',
    companyPhone: '',
    companyEmail: '',
    officialAccountLink: '',
    companyLogo: [], // 组件初始空数组
    officialAccountImg: [] // 组件初始空数组
  },
  onReset: () => {
    message.success($t('page.system_company.form.resetSuccess'));
    getCompanyInfo();
  },
  // 提交时：数组→单图URL（适配API）
  onSubmit: async (componentValues) => {
    try {
      submitting.value = true;
      // 格式转换：组件数组 → API单图URL（取第一个文件的URL，无则为null）
      const apiValues: ApiFormValues = {
        companyName: componentValues.companyName,
        companyPhone: componentValues.companyPhone,
        companyEmail: componentValues.companyEmail,
        officialAccountLink: componentValues.officialAccountLink,
        companyLogo: componentValues.companyLogo[0]?.url || null, // 数组转字符串
        officialAccountImg: componentValues.officialAccountImg[0]?.url || null // 数组转字符串
      };
      // 调用API（传递单图URL，匹配API类型）
      await fetchSaveCompanyInfo(apiValues);
      message.success($t('page.system_company.form.submitSuccess'));
    } catch (error) {
      message.error($t('page.system_company.form.submitError'));
    } finally {
      submitting.value = false;
    }
  }
});

/**
 * 获取API数据：单图URL→数组（适配组件）
 */
const getCompanyInfo = async () => {
  try {
    submitting.value = true;
    const { data } = await fetchGetCompanyInfo();
    if (data) {
      // 格式转换：API单图URL → 组件数组（单图包装成数组）
      const componentValues: ComponentFormValues = {
        companyName: data.companyName,
        companyPhone: data.companyPhone,
        companyEmail: data.companyEmail,
        officialAccountLink: data.officialAccountLink,
        // 字符串URL → 数组（组件必须数组格式）
        companyLogo: data.companyLogo
          ? [{
              id: Date.now().toString(), // 组件必须的唯一ID
              url: data.companyLogo,     // API返回的单图URL
              name: '企业Logo',
              status: 'finished'         // 组件允许的状态值（非success）
            }]
          : [],
        // 同Logo逻辑
        officialAccountImg: data.officialAccountImg
          ? [{
              id: Date.now().toString(),
              url: data.officialAccountImg,
              name: '公众号图片',
              status: 'finished'
            }]
          : []
      };
      // 赋值给组件表单（数组格式，无map错误）
      form.values.value = componentValues;
    }
  } catch (error) {
    message.error($t('page.system_company.form.fetchError'));
  } finally {
    submitting.value = false;
  }
};

// 页面挂载加载数据
onMounted(() => {
  getCompanyInfo();
});

/**
 * 填充默认值（仅非文件字段）
 */
function fillValues() {
  const defaultValues: Partial<ComponentFormValues> = {
    companyName: $t('page.system_company.enterprise.defaultName'),
    companyPhone: '13800138000',
    companyEmail: 'info@example.com',
    officialAccountLink: 'https://mp.weixin.qq.com/'
  };
  Object.assign(form.values.value, defaultValues);
}

/**
 * 文件上传：组件数组格式（避免map错误）
 */
async function handleFileUpload(path: 'companyLogo' | 'officialAccountImg', file: UploadFileInfo) {
  try {
    submitting.value = true;
    // 调用API，返回单图URL
    const { data } = await fetchUploadFile(file.file as File, path);
    if (data?.url) {
      // 包装成数组（适配组件）
      const fileItem: UploadFileInfo = {
        id: file.id, // 复用组件的文件ID（确保唯一）
        name: file.name,
        url: data.url, // API返回的单图URL
        status: 'finished', // 组件允许的状态值
        file: file.file
      };
      // 赋值数组（组件需要，无map错误）
      form.values.value[path] = [fileItem];
      message.success($t('page.system_company.upload.success'));
    }
  } catch (e) {
    message.error($t('page.system_company.upload.fail'));
  } finally {
    submitting.value = false;
  }
}

/**
 * 文件删除：重置为空数组（组件需要）
 */
function handleFileRemove(path: 'companyLogo' | 'officialAccountImg') {
  form.values.value[path] = []; // 组件需要数组格式，不能为null
}
</script>

<template>
  <ConfigProvider :locale="zhCN">
    <ProForm
      :form="form"
      :loading="submitting"
      :rules="{
        companyName: { required: true, message: $t('page.system_company.enterprise.nameRequired') },
        companyPhone: { pattern: /^1[3-9]\d{9}$/, message: $t('page.system_company.enterprise.phoneInvalid') },
        companyEmail: { pattern: /^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]{2,7}$/, message: $t('page.system_company.enterprise.emailInvalid') },
        officialAccountLink: { pattern: /^https?:\/\/.+/, message: $t('page.system_company.enterprise.linkInvalid') }
      }"
    >
      <ProCard :title="$t('page.system_company.enterprise.formTitle')" :show-collapse="false">
        <template #header-extra>
          <NFlex gap="12px" align="center">
            <NButton @click="fillValues" type="default">
              {{ $t('page.system_company.enterprise.fillValue') }}
            </NButton>
            <NButton attr-type="reset" type="default">
              {{ $t('page.system_company.form.reset') }}
            </NButton>
            <NButton attr-type="submit" type="primary" :loading="submitting">
              {{ $t('page.system_company.form.submit') }}
            </NButton>
          </NFlex>
        </template>

        <NGrid cols="1" :x-gap="16" responsive="screen">
          <!-- 企业名称 -->
          <NGi>
            <ProInput
              :title="$t('page.system_company.enterprise.name')"
              path="companyName"
              :tooltip="$t('page.system_company.enterprise.nameTip')"
            />
          </NGi>

          <!-- 企业电话 -->
          <NGi>
            <ProInput
              :title="$t('page.system_company.enterprise.phone')"
              path="companyPhone"
              :tooltip="$t('page.system_company.enterprise.phoneTip')"
            />
          </NGi>

          <!-- 企业邮箱 -->
          <NGi>
            <ProInput
              :title="$t('page.system_company.enterprise.email')"
              path="companyEmail"
              :tooltip="$t('page.system_company.enterprise.emailTip')"
            />
          </NGi>

          <!-- 企业Logo上传 -->
          <NGi>
            <ProUpload
              :title="$t('page.system_company.enterprise.logo')"
              path="companyLogo"
              :max-size="500 * 1024"
              :accept="['image/jpeg', 'image/png']"
              :upload-button-props="{ content: $t('page.system_company.upload.select') }"
              @upload="(file) => handleFileUpload('companyLogo' as const, file)"
              @remove="() => handleFileRemove('companyLogo' as const)"
            />
          </NGi>

          <!-- 公众号图片上传 -->
          <NGi>
            <ProUpload
              :title="$t('page.system_company.enterprise.officialAccountImg')"
              path="officialAccountImg"
              :max-size="1024 * 1024"
              :accept="['image/jpeg', 'image/png']"
              :upload-button-props="{ content: $t('page.system_company.upload.select') }"
              @upload="(file) => handleFileUpload('officialAccountImg' as const, file)"
              @remove="() => handleFileRemove('officialAccountImg' as const)"
            />
          </NGi>

          <!-- 公众号链接 -->
          <NGi>
            <ProInput
              :title="$t('page.system_company.enterprise.officialAccountLink')"
              path="officialAccountLink"
              :tooltip="$t('page.system_company.enterprise.linkTip')"
            />
          </NGi>
        </NGrid>
      </ProCard>
    </ProForm>
  </ConfigProvider>
</template>

<style scoped>
.n-grid-item { margin-bottom: 16px; }
</style>
